<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <AppHeader />

    <!-- 主要内容区域 -->
    <main class="container mx-auto px-4 py-6 mt-16 md:mt-20">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-900 mb-1">发布新帖子</h1>
        <p class="text-gray-500 text-sm">分享你的想法、经验或问题</p>
      </div>

      <!-- 发布表单容器 -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <form id="post-form" class="space-y-6">
          <!-- 标题输入框 -->
          <div>
            <label
              for="post-title"
              class="block text-sm font-medium text-gray-700 mb-2"
              >标题</label
            >
            <input
              type="text"
              id="post-title"
              v-model="title"
              placeholder="请输入标题（1-100字）"
              class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all"
            />
            <p class="mt-1 text-sm text-gray-500">{{ title.length }}/100</p>
          </div>

          <!-- 内容编辑器 -->
          <div>
            <label
              for="post-content"
              class="block text-sm font-medium text-gray-700 mb-2"
              >内容</label
            >
            <!-- 编辑器内容区 -->
            <textarea
              id="post-content"
              v-model="content"
              placeholder="分享你的想法..."
              class="w-full h-60 px-4 py-3 border border-gray-200 rounded-b-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none resize-none transition-all"
            ></textarea>
            <p class="mt-1 text-sm text-gray-500">{{ content.length }}/10000</p>
          </div>

          <!-- 图片上传区域 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2"
              >添加图片 (可选)</label
            >
            <div
              class="border-2 border-dashed border-gray-200 rounded-xl p-6 text-center hover:border-primary transition-colors cursor-pointer"
              @click="triggerFileUpload"
            >
              <input
                type="file"
                ref="fileInput"
                multiple
                accept="image/*"
                class="hidden"
                @change="handleFileUpload"
              />
              <div
                class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-gray-100 text-gray-500 mb-3"
              >
                <i class="fa fa-camera text-xl"></i>
              </div>
              <p class="text-gray-500">点击上传图片，或拖拽图片到此处</p>
              <p class="text-xs text-gray-400 mt-1">
                支持 JPG、PNG、GIF 格式，单张不超过 10MB，最多 9 张
              </p>
            </div>

            <!-- 已上传图片预览 -->
            <div
              v-if="images.length > 0"
              class="mt-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3"
            >
              <div
                v-for="(image, index) in images"
                :key="index"
                class="relative rounded-lg overflow-hidden bg-gray-100 aspect-square"
              >
                <img
                  :src="image.url"
                  alt="上传图片预览"
                  class="w-full h-full object-cover"
                />
                <button
                  type="button"
                  class="absolute top-2 right-2 w-6 h-6 rounded-full bg-black/50 text-white flex items-center justify-center hover:bg-black/70 transition-colors"
                  @click="removeImage(index)"
                >
                  <i class="fa fa-times text-xs"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- 分类和标签 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 分类选择 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2"
                >选择分类</label
              >
              <select
                v-model="selectedCategory"
                class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all"
              >
                <option value="">请选择分类</option>
                <option v-if="isLoadingCategories" disabled>加载中...</option>
                <option
                  v-for="category in categories"
                  :key="category.cateId"
                  :value="category.cateId"
                >
                  {{ category.cateName }}
                </option>
              </select>
            </div>
          </div>
        </form>
      </div>

      <!-- 提交按钮区域 (在所有设备上都显示在页面底部) -->
      <div class="mt-8 flex justify-center">
        <button
          class="px-10 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shadow-md hover:shadow-lg"
          :disabled="isSubmitting"
          @click="submitPost"
        >
          {{ isSubmitting ? '发布中...' : '发布帖子' }}
        </button>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import {
    createPost,
    uploadMultipleMedia,
    getCategories,
    type Category,
  } from '../services/postService'
  import AppHeader from './layout/AppHeader.vue'

  // 初始化路由
  const router = useRouter()

  // 表单数据
  const title = ref('')
  const content = ref('')
  const selectedCategory = ref('')
  const categories = ref<Category[]>([])
  const fileInput = ref<HTMLInputElement | null>(null)
  const isSubmitting = ref(false) // 添加提交状态变量
  const isUploading = ref(false) // 图片上传状态
  const isLoadingCategories = ref(false) // 分类加载状态

  // 图片上传
  interface ImageData {
    url: string
    file: File
    uploaded?: boolean // 标记是否已上传到服务器
  }
  const images = ref<ImageData[]>([])

  // 获取分类数据
  const loadCategories = async () => {
    isLoadingCategories.value = true
    try {
      categories.value = await getCategories()
    } catch (error) {
      console.error('获取分类数据失败:', error)
      ElMessage.error('获取分类数据失败')
    } finally {
      isLoadingCategories.value = false
    }
  }

  // 组件挂载时加载分类数据
  onMounted(() => {
    loadCategories()
  })

  // 方法
  const triggerFileUpload = () => {
    if (fileInput.value) {
      fileInput.value.click()
    }
  }

  const handleFileUpload = async (event: Event) => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files.length > 0 && !isUploading.value) {
      const remainingSlots = 9 - images.value.length
      const filesToAdd = Math.min(target.files.length, remainingSlots)

      if (filesToAdd > 0) {
        isUploading.value = true

        try {
          const filesArray = Array.from(target.files).slice(0, filesToAdd)

          // 先显示本地预览
          const newImages: ImageData[] = []
          filesArray.forEach(file => {
            const reader = new FileReader()
            reader.onload = e => {
              if (e.target?.result) {
                const image: ImageData = {
                  url: e.target.result as string,
                  file: file,
                  uploaded: false,
                }
                newImages.push(image)
                // 只有当所有文件都读取完成后才添加到images数组
                if (newImages.length === filesArray.length) {
                  images.value.push(...newImages)
                }
              }
            }
            reader.readAsDataURL(file)
          })

          // 上传文件到服务器
          const uploadedUrls = await uploadMultipleMedia(
            filesArray,
            'image',
            'posts'
          )

          // 更新图片URL为服务器返回的URL
          for (
            let i = 0;
            i < uploadedUrls.length && i < newImages.length;
            i++
          ) {
            const imageIndex = images.value.findIndex(
              img => img.file.name === filesArray[i].name && !img.uploaded
            )
            if (imageIndex !== -1) {
              images.value[imageIndex].url = uploadedUrls[i]
              images.value[imageIndex].uploaded = true
            }
          }

          ElMessage.success(`成功上传 ${uploadedUrls.length} 张图片`)
        } catch (error: any) {
          console.error('上传图片失败:', error)
          ElMessage.error(error.message || '图片上传失败，请重试')
          // 移除未上传成功的图片
          images.value = images.value.filter(img => img.uploaded)
        } finally {
          isUploading.value = false
        }
      }
    }
  }

  const removeImage = (index: number) => {
    images.value.splice(index, 1)
  }

  // 添加发布帖子方法
  const submitPost = async () => {
    // 表单验证
    if (!title.value.trim()) {
      ElMessage.error('请输入标题')
      return
    }

    if (title.value.length < 1 || title.value.length > 100) {
      ElMessage.error('标题长度应为1-100字')
      return
    }

    if (!content.value.trim()) {
      ElMessage.error('请输入内容')
      return
    }

    if (content.value.length > 10000) {
      ElMessage.error('内容长度不能超过10000字')
      return
    }

    if (!selectedCategory.value) {
      ElMessage.error('请选择分类')
      return
    }

    // 检查是否有未上传完成的图片
    if (images.value.some(img => !img.uploaded)) {
      ElMessage.warning('请等待图片上传完成后再发布')
      return
    }

    try {
      isSubmitting.value = true

      // 准备帖子数据
      const postData = {
        cateId: parseInt(selectedCategory.value),
        title: title.value.trim(),
        content: content.value.trim(),
        media: images.value.map(img => img.url), // 只传递图片URL
      }

      // 调用API发布帖子
      const result = await createPost(postData)

      if (result && result.success && result.code === '0') {
        ElMessage.success('帖子发布成功！')
        // 跳转到帖子详情页
        router.push(`/post/${result.data}`)
      } else {
        ElMessage.error('帖子发布失败，请重试')
      }
    } catch (error) {
      console.error('发布帖子时出错:', error)
      ElMessage.error('发布失败，请检查网络连接或稍后重试')
    } finally {
      isSubmitting.value = false
    }
  }
</script>

<style scoped>
  /* 组件特定样式 */
</style>
Error(typeof res === 'object' && res !== null && 'message' in res ? res.message
|| "评论删除失败" : "评论删除失败")
